package com.czk.netty.netty.http;

import com.czk.netty.netty.http.tomcat.MyRequest;
import com.czk.netty.netty.http.tomcat.PathScanner;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.*;
import io.netty.util.CharsetUtil;

import java.net.URI;
import java.util.Map;

/**
 * SimpleChannelInboundHandler是ChannelInboundHandlerAdapter的子类
 * HttpObject表示客户端和服务器相互通讯的数据封装成httpObject
 *
 * @Author:ChenZhangKun
 * @Date: 2021/1/14 22:00
 */
public class HttpServerHandler extends SimpleChannelInboundHandler<HttpObject> {
    /**
     * 读取客户端的数据
     *
     * @param channelHandlerContext
     * @param httpObject
     * @throws Exception
     */
    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, HttpObject httpObject) throws Exception {
        // 不同浏览器的管道是不一样的，浏览器独享一份管道
        System.out.println(channelHandlerContext.channel().pipeline().hashCode());
        // 判断是不是httpRequest请求
        if (httpObject instanceof HttpRequest) {
            System.out.println("httpObject的类型" + httpObject.getClass());
            // 客户端地址
            System.out.println("客户端地址  " + channelHandlerContext.channel().remoteAddress());
            // 得到HttpRequest对象
            HttpRequest httpRequest = (HttpRequest) httpObject;
            // 得到uri
            URI uri = new URI(httpRequest.getUri());
            // 基于netty实现tomcat
            if (uri != null) {
                // 切割
                String path = uri.getPath();
                int i = path.lastIndexOf("/");
                String url = path.substring(i);
                // 拿到处理器
                Map<String, Class> map = PathScanner.getMap();
                // 拿到对应的
                Class clazz = map.get(url);
                // 执行对应的方法
                MyRequest request = (MyRequest) clazz.newInstance();
                // 执行
                request.service(httpRequest);
            }
            // 过滤特定的资源
            if ("/favicon.ico".equals(uri.getPath())) {
                System.out.println("请求服务器图片");
                return;
            }
            // 回复信息给浏览器
            ByteBuf content = Unpooled.copiedBuffer("hello,我是服务器", CharsetUtil.UTF_8);
            // 构造一个http响应，即httpResponse
            DefaultFullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, content);
            // 设置信息
            response.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/plain");
            response.headers().set(HttpHeaderNames.CONTENT_LENGTH, content.readableBytes());
            // 将其写回
            channelHandlerContext.writeAndFlush(response);
        }
    }
}
